package com.ysyx.ysyx_admin.controller;

import com.ysyx.ysyx_admin.dto.BaseDto;
import com.ysyx.ysyx_admin.pojo.MenuPojo;
import com.ysyx.ysyx_admin.qo.AdminQo;
import com.ysyx.ysyx_admin.service.AdminPojoService;
import com.ysyx.ysyx_admin.service.MenuPojoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @description: xxxx接口/类
 * @author:Lenovo
 * @create:2023/4/17 15:32
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private MenuPojoService menuPojoService;


    @Autowired
    private AdminPojoService adminPojoService;


    @RequestMapping("/login")
    public BaseDto login(@RequestBody AdminQo adminQo, HttpSession session){
        String code = (String)session.getAttribute("code");
//        密码改成mad5
//        String md5Hex = DigestUtils.md5Hex(adminQo.getAdminPwd());
//        adminQo.setAdminPwd(md5Hex);
        System.out.println(adminQo);
        adminQo.setHttpCode(code);

        BaseDto baseDto = adminPojoService.getAdmin(adminQo);
        return baseDto;
    }


    //菜单栏数据获取
    @RequestMapping(value = "/menuList",method = RequestMethod.GET)
    public List<MenuPojo> selAllMenu() {
        System.err.println("cs=======================");
        List<MenuPojo> menuPojos = menuPojoService.showMenu();//原始的数据
        List<MenuPojo> newMenuList = new ArrayList<>();// 最后的结果

        // 先找到所有的一级菜单
        for (int i = 0; i < menuPojos.size(); i++) {
            MenuPojo pojo = menuPojos.get(i);
            int pid = pojo.getMenuPmid();
            // 如果是顶级菜单，没有父菜单
            if (pid == 0) {
                newMenuList.add(pojo);
            }
        }
        //为一级菜单设置子菜单，getChild是递归调用的
        for (MenuPojo menu : newMenuList) {
            menu.setChildren(getChild(menu.getMenuId(), menuPojos));
            System.out.println("情况" + menu);
        }

        return newMenuList;
    }



    //菜单栏递归算法
    private List<MenuPojo> getChild(int id, List<MenuPojo> rootMenu) {
        // 子菜单
        List<MenuPojo> childList = new ArrayList<>();
        for (MenuPojo menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (menu.getMenuPmid() == id) {
                childList.add(menu);
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (MenuPojo menu : childList) {
            // 没有url子菜单还有子菜单
            if (menu.getMenuUrl() == null) {
                // 递归
                menu.setChildren(getChild(menu.getMenuId(), rootMenu));
            }
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;

    }
}
